﻿/**
TODO: SessionID or RoomID
Pass the session id to server..
**/

define([
   "jQuery",
	"jQuery-ui",
    "drag",
	// "app/views/draw",  
	// "app/menu/menu-toolbox",
	// "app/menu/menu-uplimg",
	// "app/menu/menu-uplfile",
	// "app/menu/menu-page-file",
	// "app/menu/menu-save-as-file",
	// "app/menu/menu-chart-toolbox",
	// "app/menu/menu-initial-table-toolbox",
	// "app/menu/menu-pick-color-toolbox",
	// "app/menu/menu-text-logo-toolbox", 
	// "app/menu/menu-property-toolbox", 
	// "app/menu/menu-open-file-toolbox", 
	// "app/kinetic/kinetic-main",
	// "app/kinetic/kinetic-edit",
	// "kineticJs",
	"app/menu/stamp-toolbox",
	"iframeTransport",
	"app/menu/nicEdit",
	"app/text/text-main",
	"app/text/sticky-text-main",
	"rightClick",
	"touchPunch",
	"finger",
	// "colorPicker",
	"dragableTouch",
	// "colorPicker",
	"html2Canvas",
	"canvas2Image",
	// "chatbox",
	"base64Img",
	// "gridBuilder",
	"printArea",
	"app/app-util",
	], function (
    $,
	$ui,
    drag,
	// drawerView,
	// toolbox,
	// upload,
	// uploadFile,
	// pageFile,
	// saveAsFile,
	// chartToolbox,
	// initialTableToolbox,
	// pickColorToolbox,
	// textLogoToolbox,
	// propertyToolbox,
	// openFileToolbox,
	// kineticMain,
	// kineticEdit,
	// kineticJs,
	stampToolbox,
	iframeTransport,
	nicEdit,
	richText,
	stickyText,
	rightClick,
	touchPunch,
	finger,
	// colorPicker,
	dragableTouch,
	// colorPicker,
	html2Canvas,
	canvas2Image,
	// chatbox,
	base64Img,
	// gridBuilder,
	printArea,
	util
	) {
	
    return {
		lastClickPointTools:{x:0,y:0},
		lastClickPoint:{x:0,y:0},
		lastClickGlobalPoint:{x:0,y:0},
		positionChange:{left:0,top:0},
		sizeChange:{width:0,height:0},
		editProp : {x :0,y:0,width:0,height:0,bgCanvas:""},
		fileId: "fileId",
		// kinetic: kineticMain,
		// kineticEdit : kineticEdit,
		// toolbox : toolbox,
		// richText : richText,
		// stickyText : stickyText,
		// upload : upload,
		// uploadFile : uploadFile,
		// pageFile : pageFile,
		// saveAsFile : saveAsFile,
		// chartToolbox : chartToolbox,
		// initialTableToolbox : initialTableToolbox,
		// pickColorToolbox : pickColorToolbox,
		// textLogoToolbox : textLogoToolbox,
		// propertyToolbox : propertyToolbox,
		// openFileToolbox : openFileToolbox,
		Util : util,
		// draw: drawerView,
		rootCanvas : 'rootContainer',
		kineticCanvas: 'kineticCanvas',
		stampToolbox : stampToolbox,
		kineticExporterCanvas : 'kineticExporterCanvas',
		dragMode: true,
		activeObject : false,
		isDrag:false,
		lastUpdateTime:0,
		prepareCreation:false,
		creationMode:false,
		creationKind: false,//'shape',//shape,text,stamp
		creationType:'pencil',
		creationStartPoint: {x:0,y:0},
		creationObject: null,
		pollInterval: 25000000,
		openedTool: false,
		option : false,
		heightChartDraw : 0,
		widthChartDraw : 0,
		listFileLayersCount : 0,
		tempPageId : false, 
		openWindowPreview : 1,
		// chatbox:chatbox,
		initialWidth : 0,
		chatboxContainer:null,
		isUpdate : 0,
		lastZ : 20,
		idIndicatorLast : 0,
		idPageSelcLast : 0,
		isPrintPage : 0,
		pageIdData : [],
		pages : new Array(),
		printObject:0,
		contentGlobal:false,
		lastIdx:[],
		baseUrl:document.getElementById("base_url").value,
		fileId:document.getElementById("file_id").value,
		pageId:document.getElementById("page_id").value,
		username:document.getElementById("u_name").value,
		userId:document.getElementById("u_id").value,
		nodeURL:document.getElementById("node_url").value,
		isTemplate:document.getElementById("is_template").value,

        init: function () { 
			// alert($('#rootContainer').html());
			// App.baseUrl;
			App.pageIdPrint(); 
			// App.loadDataPrintTable();
			initialWidth = $(window).width();
			 if(App.isTemplate == 0)
			 	App.isTemplate = false
			 else
				App.isTemplate=true;
			App.socket=io.connect('http://54.244.179.184:4000');
			 // App.socket=io.connect('http://220.110.178.121:4000');
			// App.socket=io.connect('http://103.28.149.218:4000');
				// $("#overlay").hide();
			App.socket.on('connected', function(data){
				// $("#overlay").hide();
				App.socket.emit('cm_auth', {roomid: App.fileId, page: App.pageId, username: App.username, userid: App.userId});
			});
			$(function () {
				$('#select-print-button').click(
					function() {
						$('.tf').attr('checked', 'checked');
						var sizeCheck = App.pageIdData.length;
						// var countData = 0;
						
						$('.DocView').children().remove();
						$('.DocView').css('display','block');
						for(countData = 0; countData < sizeCheck; countData++){
							$('<img></img>').attr({ id:"img_"+countData, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[countData]+'.png'}).css({width:'100%'}).appendTo($('.DocView')); 
							$('<img></img>').attr({ id:"img_"+countData, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[countData]+'.png'}).css({width:'100%'}).appendTo($('.DocViewHide')); 
						}
					} 
				);
			});	
			$(function () {
				$('#des-print-button').click(function () {
					$('.tf').removeAttr('checked');
					$('.DocView').find($('.imagePreview')).remove();
					$('.DocViewHide').find($('.imagePreview')).remove();
				});
			});
			$(function () {
				$('#print-button').click(function () { 
					$('.imagePreview').css("display"," ");
					
					$('.DocViewHide').printArea();
					// $('.DocViewHide').css("display","none");
				});
			});	
			$(function () {
				$('#cancel-button').click(function () { 
					window.close();
				});
			});	
			
			 
			App.socket.on('sm_auth', function(data){
				console.log("Connected To Server...")
				$("#overlay-event").hide();
				
				// App.chatboxContainer = $("#chat_div").chatbox({id:App.username, 
                                                // user:{key : "value"},
                                                // title : "Chat Box",
                                                // messageSent : function(id, user, msg) {
                                              	 	 // var cObj = {username:App.username,message:msg};
                                              	 	 // var url = App.baseUrl+"CommHub/add_chat_history";
													 // var data = {"last_update_time": App.lastUpdateTime,
														// "file_id":  App.fileId,
														// "user_id":  App.userId,
														// "message": msg
														// };
													 // console.log(App.pageId);		
													 // var request=$.ajax({
														// type: 'POST',
														// url: url,
														// data:data,
													 // });	
                                                	 // App.socket.emit('cm_chat', {roomid: App.fileId, objects:cObj, id: App.userId}); 
													 // $("#chat_div").chatbox("option", "boxManager").addMsg(id, msg);
                                                // }});
			});
			 
			App.socket.on('sm_object_send',function(data){
			console.log("sm_object_send");
			
				if(data.kind == "text"){
					if(data.cmd == "content-update"){
						$("#text_content_"+data.id).html(data.object);
						$(".resize-grip"+data.id).hide();
					}
				}
			});
			 
			
			// kineticMain.init();
			// drawerView.init();
			// toolbox.init();
			 
			 
			// var intval = setInterval("App.htmlToImage(App.pageId)", 5000);
			// var intval = setInterval(function(){
										// if(App.creationKind != "shape"){
											// App.htmlToImage(App.pageId)
										// }
									// }, 30000);
			 
			// document.getElementById(App.kineticCanvas).style.display = "none";
			// document.getElementById(App.kineticExporterCanvas).style.display = "none";
			
			// var refreshId = setInterval("test()", 5000);
			 
            
                                         
		},
		toggle_visibility:function(id){
		console.log("toggle");
		console.log($('#'+id));
			$('#'+id).toggle();
		},  
		
		 
		
		loadTextObject:function(data){ 
			
			var style = ""; 
			var color = "";
			if(data.object_type == "buble"){
				
				//rheo,bubble ganti stick
				style = 'class="sticky taped"';
				color = '#F4F39E';
				if(data.kind){
					if(data.kind == "bubble2"){
						color = '#d6f0fa';
					}else if(data.kind == "bubble3"){
						color = '#f5d1f5';
					}else if(data.kind == "bubble4"){
						color = '#cffdc9';
					}else if(data.kind == "bubble5"){
						color = '#d5cdfe';
					}
				}
			}
			
			var newTextObject =  $('<div ' + style + '></div>')
									.attr("id",data.id)
									.attr("object_type",data.object_type)
									.addClass("nic-edit-element")//.appendTo($('#rootPrintContainer'))
									.css("overflow","visible")
									.css("z-index","18"); 
			if(data.object_type == "buble")
			{
				newTextObject.attr("kind",data.kind);
				newTextObject.css("background-color",color);
			}
			newTextObject.css("left",(parseInt(data.posx)));
			newTextObject.css("top",(parseInt(data.posy)));
			newTextObject.css("height",parseInt(data.height));
			newTextObject.css("width",parseInt(data.width));
			newTextObject.css("overflow","visible");
			
			newTextObject.html("<div id='text_content_"+data.id+"' style='overflow:hidden;width:100%;height:100%;'>" + data.content + "</div>");
			$("#"+data.id).css("position", "");
			 
			if(App.printObject == 0){ 
				newTextObject.appendTo($('#rootPrintContainer'));
			}else{ 
				return newTextObject;
			}
		},
		
		loadStickyTextObject:function(data){
			// if(App.isPrintPage == 1)
			// {
				var newStickyTextObject =  $('<div></div>')
										.attr("id",data.id)
										.attr("object_type",data.object_type)
										.addClass("nic-sticky-edit-element").appendTo($('#rootPrintContainer'));

			// }
			// else
			// {
				// var newStickyTextObject =  $('<div></div>')
										// .attr("id",data.id)
										// .attr("object_type",data.object_type)
										// .addClass("nic-sticky-edit-element").appendTo($('#rootContainer'));
			// }
			newStickyTextObject.css("left",(parseInt(data.posx)));
			newStickyTextObject.css("top",(parseInt(data.posy)));
			newStickyTextObject.css("height",parseInt(data.height));
			newStickyTextObject.css("width",parseInt(data.width));
			newStickyTextObject.css("background",data.background);
			newStickyTextObject.css("overflow","visible");
			newStickyTextObject.html("<div id='text_content_"+data.id+"' style='overflow:hidden;width:100%;height:100%;'>" + data.content + "</div>");
			$("#"+data.id).css("position", "");
			
		
			  
		},
		
		disableclick:function(e){
			// alert(e.button);
			if(e.button==2)
			{
				// alert(status);
				return false;    
			}
		},
		
	
		 	
			
		loadDrawingObject : function(data){  
			//console.log(data);
			// if(App.isPrintPage == 1)
			// {
				var newImgContainer = $('<div></div>').attr({'id':data.id,'class':'image', 'type':data.type, 'object_type':data.type, 'created_by':data.created_by, 'created_date':data.created_date}).appendTo($('#rootPrintContainer'));
			// }
			// else
			// {
				// var newImgContainer = $('<div></div>').attr({'id':data.id,'class':'image', 'type':data.type, 'object_type':data.type, 'created_by':data.created_by, 'created_date':data.created_date}).appendTo($('#rootContainer'));
			// }
			newImgContainer.css("position","absolute");
			newImgContainer.css("left",(parseInt(data.posx)));
			newImgContainer.css("top",(parseInt(data.posy)));
			newImgContainer.css("height",parseInt(data.height));
			newImgContainer.css("width",parseInt(data.width));
			newImgContainer.css("overflow","visible");
		
			var newImgComponent = $('<img></img>').attr({ 'src': App.baseUrl+data.image_url,'id':"img"+data.id}).appendTo(newImgContainer);
			newImgComponent.attr({ 'src': App.baseUrl+data.image_url,'id':"img"+data.id});
			// newImgContainer.append(newImgComponent); 
			
			
			 
			// $(".resize-grip"+data.id).hide();

		   
		},
		
		loadTableObject:function(data){
			// if(App.isPrintPage == 1)
			// {
				var newTableContainer = $('<div></div>').attr({'id':data.id,'class':'table','type':data.type, 'object_type':data.object_type}).appendTo($('#rootPrintContainer'));
			// }
			// else
			// {
				// var newTableContainer = $('<div></div>').attr({'id':data.id,'class':'table','type':data.type, 'object_type':data.object_type}).appendTo($('#rootContainer'));
			// }
			newTableContainer.css("position","absolute");
			newTableContainer.css("left",(parseInt(data.posx)));
			newTableContainer.css("top",(parseInt(data.posy)));
			newTableContainer.css("height", (parseInt(data.height)));
			newTableContainer.css("width", (parseInt(data.width)));
			newTableContainer.css("overflow","visible");
			
			newTableContainer.css("cursor", 'default');
			newTableContainer.css("border", '1px solid rgb(160, 160, 164)');
			
			// mytable = $('<table></table>').attr({ id: "tbl_"+tblId, border:"2px"});
			
			// var contentTable = 
			var tableConteiner = $('<table></table>').attr({ id: "tbl_"+data.id, border:"2px", width:"100%", height:"100%"}).html(data.content_table).appendTo(newTableContainer);
			
			 
		},
		
		loadChartObject : function(data){
		
			// if(App.isPrintPage == 1)
			// {
				var newChartContainer = $('<div></div>').attr({'id':data.id,'class':'image','type':data.type, 'object_type':data.object_type, 'chart-data':data.data_chart}).appendTo($('#rootPrintContainer'));
			// }
			// else
			// {
				// var newChartContainer = $('<div></div>').attr({'id':data.id,'class':'image','type':data.type, 'object_type':data.object_type, 'chart-data':data.data_chart}).appendTo($('#rootContainer'));
			// }
			newChartContainer.css("position","absolute");
			newChartContainer.css("left",(parseInt(data.posx)));
			newChartContainer.css("top",(parseInt(data.posy)));
			newChartContainer.css("height",parseInt(data.height));
			newChartContainer.css("width",parseInt(data.width));
			newChartContainer.css("overflow","visible");
			var newChartImgContainer = $('<img></img>').attr({ 'src': App.baseUrl+data.image_url,'id':"img"+data.id}).appendTo(newChartContainer);
			
			 
		},
		
		 
		
		 
		
		prepareTextCreation: function(creation){
			App.prepareCreation = creation;
			App.creationKind = "text";
			App.creationType = "text";
		},
		
		prepareBubleTextCreation: function(creation){
			App.prepareCreation = creation;
			App.creationKind = "buble";
			App.creationType = "buble";
		},
		
		prepareStickyTextCreation: function(creation){
			App.prepareCreation = creation;
			App.creationKind = "sticky-text";
			App.creationType = "";
		},
		
		setEnableKineticCreationMode: function(creation,shouldSave){
			App.creationMode = creation;
			if(App.creationMode){
				document.getElementById(App.rootCanvas).style.display = "none";
				document.getElementById(App.kineticCanvas).style.display = "block";
				App.kinetic.setStageSize({width:970,height:600});
				$("#" + App.kineticCanvas).css({"border":"1px solid black","width":"970","height":"600"});
				$("#" + App.kineticCanvas).offset({top:110,left:130});
				App.kinetic.enterCreationMode();
				
			}else{
				document.getElementById(App.rootCanvas).style.display = "block";
				document.getElementById(App.kineticCanvas).style.display = "none";
				App.kinetic.endCreationMode(shouldSave);
			}
		},
		
		setEnableKineticEditCreationMode: function(creation,shouldSave){
			console.log("Enable Kinetic Mode For Edit");
			App.creationMode = creation;
			if(App.creationMode){
				App.activeObject.hide();
				App.kinetic.enterCreationMode();
				//document.getElementById(App.rootCanvas).style.display = "none";
				document.getElementById(App.kineticCanvas).style.display = "block";
				App.kinetic.setStageSize({width:App.editProp.width,height:App.editProp.height});
				// alert(App.editProp.bgCanvas);
				App.kinetic.setBGCanvas(App.editProp.bgCanvas,{width:App.editProp.width,height:App.editProp.height});
				$("#" + App.kineticCanvas).css({"border":"3px solid red","width":App.editProp.width,"height":App.editProp.height});
				$("#" + App.kineticCanvas).offset({top:App.editProp.y,left:App.editProp.x});
			}else{
				if(shouldSave)
					App.activeObject.remove();
				else
					App.activeObject.show();
				//document.getElementById(App.rootCanvas).style.display = "block";
				document.getElementById(App.kineticCanvas).style.display = "none";
				App.kinetic.endCreationMode(shouldSave);
			}
		},
		
		setEnableStampCreationMode: function(creation,stampImage){
			App.creationMode = creation;
			if(App.creationMode)
				App.setCreationObject("stamp",stampImage);
			
		},
		
		setCreationObject : function(kind,type){
			App.creationKind = kind;
			App.creationType = type;
			console.log("Enter Creation : " + kind + " - " + type);
		},
				
		setEnableImageCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
				App.setCreationObject("image");
		},
		
		setEnableFileCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
				App.setCreationObject("file");
		},
		
		setEnableChartCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
				App.setCreationObject("chart");
		},
		
		setEnableTableCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
				App.setCreationObject("table");
		},
		
		setEnableTextLogoCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
				App.setCreationObject("text-logo");
		},
		
		touchStartCanvas: function(){
			
		},
		
		touchMoveCanvas: function(){
			
		},
		
		touchEndCanvas: function(){
			
		},
		
		 
		
		pickColor:function(id){
			App.pickColorToolbox.show();
		},
		
		pickColorSelected:function(){			
			// console.log(App.pickColorToolbox.color);
			var hex = App.pickColorToolbox.color;
			if(hex.charAt(0) == "#") hex = hex.slice(1); //Remove the '#' char - if there is one.
			hex = hex.toUpperCase();
			var hex_alphabets = "0123456789ABCDEF";
			var value = new Array(3);
			var k = 0;
			var int1,int2;
			for(var i=0;i<6;i+=2) {
				int1 = hex_alphabets.indexOf(hex.charAt(i));
				int2 = hex_alphabets.indexOf(hex.charAt(i+1)); 
				value[k] = (int1 * 16) + int2;
				k++;
			}
			console.log(value[0]);
		},
		
		 
		
		bringToFront:function(){
			if(App.activeObject)
			{
				App.activeObject.css({"z-index":parseInt(App.lastZ) + 1});
				App.lastZ++;
			}
			
		},
		
		sendToBack:function(){
			if(App.activeObject)
			{
				App.activeObject.css({"z-index":"10"});
			}	
		},
		
		 
							
		showLoading:function(){
			// $("#window").kendoWindow({
				// draggable: false,
				// height: "100px",
				// modal: true,
				// resizable: false,
				// title: false,
				// title: "Please Wait...",
				// width: "500px"
			// }).data("kendoWindow").center();
					
		},
		
		hideLoading:function(){
			// var window = $("#window");
			// window.data("kendoWindow").close();
		},
		
		 
						
		colorPickerSelected:function(){
			$('.jPicker').jPicker(
			{
			  window:
			  {
				expandable: true
			  }
			});
		},
		
		htmlToImage:function(currPageId){ 
			html2canvas(document.getElementById('rootContainer'), {
				onrendered: function(canvas) { 
					var dataImg = Canvas2Image.convertToPNG(canvas, 80, 60);
					var dataURL = dataImg.src; 
					var newImagePath = "documents/"+App.fileId+"/thumb-"+currPageId+".png";
					
					var url = App.baseUrl+"CommHub/add_thumb_canvas";
					var allData = {"file_id": App.fileId,
									"page_id": currPageId,
									"filepath" : newImagePath,
									"image_data": dataURL
								};
					var request = $.ajax({ //get data awal
									url: url,
									type: "POST",
									data: allData,
								});
					
					request.done(function(msg) {   
						var existingObject=false;	//check if it's an existing object
							$('.layerboxContainer').children().each(function(){
								if($(this).attr('id') == "page_"+currPageId)
								{
									existingObject=$(this);
								}
							});
							if(existingObject)
							{ 
								 $("#page"+currPageId).attr('src',(App.baseUrl+newImagePath+"?dum="+(new Date).getTime())); 
							}
							// setTimeout("App.htmlToImage(App.pageId)", 2000);
					});
					request.fail(function(jqXHR, textStatus) { 
					});
					request.always(function(){
					});
				}
			});
			// var urlImage = "documents/"+App.fileId+"/thumb-"+App.pageId+".png";
		},
				
		   
		
		printWorkspaces:function(){
			var my_window = false;
			my_window = window.open(App.baseUrl+"home/draw_preview?f_id="+App.fileId, "DigitalBoard", "status=1,width=250,height=160");
			
		},
		
		pageIdPrint:function(){
			
			// var url = App.baseUrl+"CommHub/page_id_by_file/"; 
			// var allData = {
					// "file_id": App.fileId,
			// }; 
			// var request =$.ajax({
					// type: 'POST',
					// url: url,
					// data:allData
				// });
			// request.done(function(msg) { 
			
			// });
			// request.fail(function(jqXHR, textStatus) {
			// });
			// request.always(function(){
			// });
			
			// App.isPrintPage = 1;
			
			var url = App.baseUrl+"CommHub/get_file_data";
			var allData = {"file_id": App.fileId}
			
			var request = $.ajax({ //get data awal
				url: url,
				type: "POST",
				data: allData,
			});
			request.done(function(msg) { 
				var jsonObject = JSON.parse(msg); 
				var contentObject = JSON.parse(jsonObject.content);  
				App.lastUpdateTime=jsonObject.last_update;
				var objectArray=[];
				var printPage = 0;
				App.htmlToImagePrintRecurse(contentObject,0); 
				
				// $('#rootPrintContainer').hide();
				// $('#DoView').hide();
				
				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		htmlToImagePrintRecurse:function(contentObject,pageIndex){
				// alert(pageIndex);
				// alert(contentObject.pages.length);
				if(pageIndex >= contentObject.pages.length)
				{
					// alert("eksekeusi");
					$("#overlay").hide();
					App.loadDataPrintTable();
					return;
				}
				
				indexKe = pageIndex + 1;
				App.pageIdData.push(indexKe);
				$('#rootPrintContainer').children().remove();
				for(var objectIndex=0;objectIndex<contentObject.pages[pageIndex].drawing_objects.length;objectIndex++)
				{ 
			
					if((contentObject.pages[pageIndex].drawing_objects[objectIndex]).type=="image"){ 
						App.loadDrawingObject(contentObject.pages[pageIndex].drawing_objects[objectIndex]);
					}
					if((contentObject.pages[pageIndex].drawing_objects[objectIndex]).type=="attach"){
						App.loadDrawingObject(contentObject.pages[pageIndex].drawing_objects[objectIndex]);
					}
					if((contentObject.pages[pageIndex].drawing_objects[objectIndex]).type=="text" || 
						(contentObject.pages[pageIndex].drawing_objects[objectIndex]).type=="buble"){ 
						App.loadTextObject(contentObject.pages[pageIndex].drawing_objects[objectIndex]);
					}
					if((contentObject.pages[pageIndex].drawing_objects[objectIndex]).type=="chart"){ 
						App.loadChartObject(contentObject.pages[pageIndex].drawing_objects[objectIndex]);
					}
					if((contentObject.pages[pageIndex].drawing_objects[objectIndex]).type=="sticky-text"){
						App.loadStickyTextObject(contentObject.pages[pageIndex].drawing_objects[objectIndex]);
					}
					if((contentObject.pages[pageIndex].drawing_objects[objectIndex]).type=="table"){
						App.loadTableObject(contentObject.pages[pageIndex].drawing_objects[objectIndex]);
					} 
				}   
				
				html2canvas(document.getElementById('rootPrintContainer'), { 
					onrendered: function(canvas) {  
						var dataImg = Canvas2Image.convertToPNG(canvas, 940, 640);
						var dataURL = dataImg.src; 
						var indexPage = pageIndex + 1;
						var newImagePath = "documents/"+App.fileId+"/print-"+indexPage+".png";
						// alert(newImagePath);
						var url = App.baseUrl+"CommHub/add_thumb_canvas";
						var allData = {"file_id": App.fileId,
										"page_id": pageIndex,
										"filepath" : newImagePath,
										"image_data": dataURL
									};
						var request = $.ajax({ //get data awal
										url: url,
										type: "POST",
										data: allData,
									});
						
						request.done(function(msg) {  
							// alert("Tes");
							var existingObject=false;	//check if it's an existing object 
							pageIndex+=1;
							App.htmlToImagePrintRecurse(contentObject,pageIndex);
						});
						request.fail(function(jqXHR, textStatus) {  
						});
						request.always(function(){
						});
					}
				});
		
		},
		
		loadDataPrintTable:function(){ 
			// alert("load");
			// var url = App.baseUrl+"CommHub/add_data_table";
			// var allData = {"file_id": App.fileId,
							// "page_id_data": App.pageIdData,
						// };
			// var request = $.ajax({ //get data awal
							// url: url,
							// type: "POST",
							// data: allData,
						// });
			
			// request.done(function(msg) {  
			$('#rootPrintContainer').hide();
			// });
			// request.fail(function(jqXHR, textStatus) {  
			// });
			// request.always(function(){
			// });
			// alert(App.pageIdData);
			var sizeData = App.pageIdData.length;
			// alert(sizeData);
			var trSize = 1;
			var dataKe = 1;
			var tr = [];
			var row = $('<tr></tr>').attr({ id: 'pageList'+trSize+'_trID' }).appendTo($('#pageList'));
			for (var i = 0; i < sizeData; i++) {
				console.log(i);
				if( trSize > 5){ 
					trSize = 1;
					var row = $('<tr></tr>').attr({ id: 'pageList'+trSize+'_trID' }).appendTo($('#pageList'));
				} 
				var column = $('<td style="text-align:center"></td>').appendTo(row);  
				$('<img></img>').attr({ src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[i]+'.png'}).css({height:'80px'}).appendTo(column);  
				var checkbutton = $('<input></input>').attr({type:'checkbox', id:'checkbox_'+i, class:'tf'}).css({height:'80px'}).appendTo(column); 
				
				checkbutton.on('tap',function(e){ 
				if( !(navigator.userAgent.match(/Android/i)
					|| navigator.userAgent.match(/webOS/i)
					|| navigator.userAgent.match(/iPhone/i)
					|| navigator.userAgent.match(/iPad/i)
					|| navigator.userAgent.match(/iPod/i)
					|| navigator.userAgent.match(/BlackBerry/i)
					|| navigator.userAgent.match(/Windows Phone/i)
				  ))
				{ 
					var indexKe = parseInt($(this).attr("id").substring(9)); 
					console.log($(this));
					if (!$(this).attr("checked")) {
						// var indexFind = indexKe + 1;
						App.lastIdx.push(indexKe);
						console.log(App.lastIdx);
						if($('.DocView').find($('#img_'+indexKe)).attr('id') != "img_"+App.pageIdData[indexKe]){ 
							// $('.imagePreview').css('display','none');
							// $('.DocView').children().remove();
							$('.DocView').css('display','block');
							$('<img></img>').attr({id:"img_"+indexKe, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[indexKe]+'.png'}).css({width:'100%'}).appendTo($('.DocView'));
							$('<img></img>').attr({id:"img_"+indexKe, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[indexKe]+'.png'}).css({width:'100%'}).appendTo($('.DocViewHide'));  
							 
						// }else{
							// $('.DocView').css('display','block');
							// $('<img></img>').attr({id:"img_"+indexKe, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[indexKe]+'.png'}).css({width:'100%'}).appendTo($('.DocView')); 
							// $('<img></img>').attr({id:"img_"+indexKe, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[indexKe]+'.png'}).css({width:'100%'}).appendTo($('.DocViewHide'));  
						}
					}else{  
						// $('.DocView').find($('#img_'+indexKe)).remove();
						// $('.DocViewHide').find($('#img_'+indexKe)).remove();
						
						var indexTo = 0;
						indexTo = indexKe - 1;
						var viewIndx = i - 2;   
						
						var alreadyIndex = false;
						var checkIdx = -1;
						// alert(indexKe);
						
						// alert(indexKe);
						for(var indexLast = 0;App.lastIdx.length;indexLast++){
							// alert(App.lastIdx[indexLast]);
							// alert(indexTo);
							if(App.lastIdx[indexLast] == indexKe){
								checkIdx = indexLast;
								alreadyIndex = true;
								break;
							}
						}
						
						if(alreadyIndex){
							// alert(App.lastIdx[checkIdx]);
							$('.DocView').find($('#img_'+App.lastIdx[checkIdx])).remove();
							$('.DocView').children().remove();
							
							$('.DocViewHide').find($('#img_'+App.lastIdx[checkIdx])).remove();
							App.lastIdx.splice(checkIdx,1); 
							// $('.imagePreview').css("display","none"); 
							$('<img></img>').attr({id:"img_"+App.lastIdx[App.lastIdx.length-1], class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[App.lastIdx[App.lastIdx.length-1]]+'.png'}).css({width:'100%'}).appendTo($('.DocView'));
							// $('.DocView').find($('#img_'+App.lastIdx[App.lastIdx.length-1])).css("display","block");
						}
					}
				}
				else
				{
					var indexKe = parseInt($(this).attr("id").substring(9)); 
					console.log($(this));
					if (!$(this).attr("checked")) {   
						if(indexKe == 0){ 
							$('.DocView').children().remove();
							$('.DocView').css('display','block');
							$('<img></img>').attr({ id:"img_"+indexKe, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[indexKe]+'.png'}).css({width:'100%'}).appendTo($('.DocView'));  
							$('<img></img>').attr({ id:"img_"+indexKe, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[indexKe]+'.png'}).css({width:'100%'}).appendTo($('.DocViewHide'));  
							 
						}else{
							$('.DocView').css('display','block');
							$('<img></img>').attr({ id:"img_"+indexKe, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[indexKe]+'.png'}).css({width:'100%'}).appendTo($('.DocView')); 
							$('<img></img>').attr({ id:"img_"+indexKe, class:"imagePreview", src: App.baseUrl+'documents/'+App.fileId+'/print-'+App.pageIdData[indexKe]+'.png'}).css({width:'100%'}).appendTo($('.DocViewHide'));  
						}
					}else{
						$('.DocView').find($('#img_'+indexKe)).remove();
						$('.DocViewHide').find($('#img_'+indexKe)).remove();
					}
					
				}
			});
				trSize = trSize + 1; 
			}
		}
	
	}
});